///
///  NSString+CZ.m
///
///  Created by Vincent_Guo on 14-6-28.
///  Copyright (c) 2014年 vgios. All rights reserved.
///

#import "NSString+CZ.h"
#import "NSDate+Extension.h"
#import <CommonCrypto/CommonDigest.h>



@implementation NSString (CZ)


+(NSString *)getMinuteSecondWithSecond:(NSTimeInterval)time{
    
    int minute = (int)time / 60;
    int second = (int)time % 60;
    
    if (second > 9) { ///2:10
        return [NSString stringWithFormat:@"%d:%d",minute,second];
    }
    
    ///2:09
    return [NSString stringWithFormat:@"%d:0%d",minute,second];
}


+ (NSString *)readFromLibraryDirectory:(NSString*)filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    
    NSString *CachesDirectory = [paths objectAtIndex:0];
    
    NSString *path = [CachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",filename]];
    
    return path;
}


+ (NSString *)deletSpaceInString:(NSString *)text andIsAll:(BOOL )all
{
    NSString *content = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];/// 去除首尾 空格和换行
    NSString *replace = [content stringByReplacingOccurrencesOfString:@" " withString:@""];/// 去全部空格
    
    if (all) {
        return replace;
    }
    return content;
}


+ (NSString *)cutOutString:(NSString *)string Char:(NSString *)chars
{
    NSArray *strings = [string componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"。."]];
    
    NSString *periodString = [strings firstObject];
    
    return periodString;
}

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

#pragma mark - 解析HTML
+ (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim
{
    NSScanner *theScanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    
    while ([theScanner isAtEnd] == NO)
    {
        /// find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        /// find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        /// replace the found tag with a space
        ///(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:@"%@>", text] withString:@""];
        
        if ([html containsString:@"</p><p>"]) {
            NSString *replace = [html stringByReplacingOccurrencesOfString:@"</p><p>" withString:@"\n"];
            
            html = replace;
        }
        if ([html containsString:@"&nbsp;"])
        {
            NSString *replace = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
            html = replace;
        }
        if ([html containsString:@"_ueditor_page_break_tag_"])
        {
            NSString *replace = [html stringByReplacingOccurrencesOfString:@"_ueditor_page_break_tag_" withString:@" "];
            
            html = replace;
        }
        
        
    }
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}



+ (NSString *)setCount:(int)count title:(NSString *)title
{
    /// 数字不为0
    if (count < 10000)
    { /// 不足10000：直接显示数字，比如786、7986
        title = [title stringByAppendingString:[NSString stringWithFormat:@" %d", count]];
    }
    else
    { /// 达到10000：显示xx.x万，不要有.0的情况
        double wan = count / 10000.0;
        title = [title stringByAppendingString:[NSString stringWithFormat:@" %.1f万", wan]];
        /// 将字符串里面的.0去掉
        title = [title stringByReplacingOccurrencesOfString:@" .0" withString:@""];
    }
    
    return title;
}


/**
 1.今年
 1> 今天
 * 1分内： 刚刚
 * 1分~59分内：xx分钟前
 * 大于60分钟：xx小时前
 
 2> 昨天
 * 昨天 xx:xx
 
 3> 其他
 * xx-xx xx:xx
 
 2.非今年
 1> xxxx-xx-xx xx:xx
 */

+ (NSString *)createTime:(NSString *)createTime
{
    NSString *returnTime = [NSString stringWithFormat:@"%@", createTime];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 如果是真机调试，转换这种欧美时间，需要设置locale
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    /// 设置日期格式（声明字符串里面每个数字和单词的含义）
    /// E:星期几
    /// M:月份
    /// d:几号(这个月的第几天)
    /// H:24小时制的小时
    /// m:分钟
    /// s:秒
    /// y:年
    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    ///    _created_at = @"Tue Sep 30 17:06:25 +0600 2014";
    
    /// 微博的创建日期
    NSDate *createDate = [fmt dateFromString:returnTime];
    /// 当前时间
    NSDate *now = [NSDate date];
    
    /// 日历对象（方便比较两个日期之间的差距）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /// NSCalendarUnit枚举代表想获得哪些差值
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    /// 计算两个日期之间的差值
    NSDateComponents *cmps = [calendar components:unit fromDate:createDate toDate:now options:0];
    
    if ([createDate isThisYear])
    { /// 今年
        if ([createDate isYesterday])
        { /// 昨天
            fmt.dateFormat = @"昨天 HH:mm";
            return [fmt stringFromDate:createDate];
        }
        
        else if ([createDate isToday])
        { /// 今天
            if (cmps.hour >= 1)
            {
                return [NSString stringWithFormat:@"%d小时前", (int)cmps.hour];
            }
            
            else if (cmps.minute >= 1)
            {
                return [NSString stringWithFormat:@"%d分钟前", (int)cmps.minute];
            }
            
            else
            {
                return @"刚刚";
            }
        }
        else
        { /// 今年的其他日子
            fmt.dateFormat = @"MM-dd HH:mm";
            return [fmt stringFromDate:createDate];
        }
    }
    
    else
    {
        /// 非今年
        fmt.dateFormat = @"yyyy-MM-dd HH:mm";
        return [fmt stringFromDate:createDate];
    }
}

+ (NSString *)getYMDHM:(NSString *)timeStr {
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:timeStr];
    
    NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"M月d EEEE H:mm"];
    
    NSString *string=[dateFormatter1 stringFromDate:date];
    
    return string;
    
    
}
//将某个时间戳转化成 时间
+(NSString *)timestampSwitchTime:(double)timestamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //yyyy-MM-dd HH:mm
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp/1000];
    
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    return confromTimespStr;
    
}

/** md5 一般加密 */

+ (NSString *)MD5String:(NSString *)string
{
    const char *myPasswd = [string UTF8String];
    
    unsigned char mdc[16];
    
    CC_MD5(myPasswd, (CC_LONG)strlen(myPasswd), mdc);
    
    NSMutableString *md5String = [NSMutableString string];
    
    for (int i = 0; i< 16; i++)
    {
        [md5String appendFormat:@"%02x",mdc[i]];
    }
    
    return md5String;
    
}

/** md5 NB(牛逼的意思)加密*/
+ (NSString *)MD5StringNB:(NSString *)string
{
    const char *myPasswd = [string UTF8String];
    
    unsigned char mdc[16];
    
    CC_MD5(myPasswd, (CC_LONG)strlen(myPasswd), mdc);
    
    NSMutableString *md5String = [NSMutableString string];
    
    [md5String appendFormat:@"%02x",mdc[0]];
    
    for (int i = 1; i< 16; i++)
    {
        [md5String appendFormat:@"%02x",mdc[i]^mdc[0]];
    }
    
    return md5String;
}

/** * 随机生成字符串 */
+ (NSString *)generateRandomString
{
    ///    char data[32];
    ///
    ///    for (int x=0;x<32;data[x++] = (char)('A' + (arc4random_uniform(26))));
    ///    NSString *randomString = [[NSString alloc] initWithBytes:data length:8 encoding:NSUTF8StringEncoding];
    
    
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < 32; i++)
    {
        int number = arc4random() % 36;
        if (number < 10)
        {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }
        else
        {
            int figure = (arc4random() % 26) + 'a';
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    
    return string;
}



#pragma mark ---- 判断邮箱格式  ----
+ (BOOL)CheckInputEmail:(NSString *)email
{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}

#pragma mark ---- 英文数字. 下划线, 横线  ----
+ (BOOL)checkUserNameWithChar:(NSString *)text
{
    NSString *Regex = @"^[a-zA-Z0-9_\\-\u4e00-\u9fa5]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    BOOL isCheck = [emailTest evaluateWithObject:text];
    return isCheck;
}


//+ (NSString *)userNameString
//{
//    NSString *nameString;
//    
//    if ([USERID length]!=0)
//        
//    {
//        if ([NICKNAME length])
//        {
//            nameString = NICKNAME;
//        }
//        
//        else if ([USERNAME length])
//        {
//            nameString = USERNAME;
//        }
//        
//    }
//    
//    else
//    {
//        nameString=@"未登录";
//    }
//    return nameString;
//    
//}

+ (NSString *)cutOutStringWithPeriod:(NSString *)string
{
    NSArray *strings = [string componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"。."]];
    
    NSString *periodString = [strings firstObject];
    
    return periodString;
}


+ (NSMutableAttributedString *)attributedString:(NSString *)imageName text:(NSString *)textStr font:(CGFloat)fontSize color:(UIColor *)color
{
    return [self attributedString:imageName text:textStr font:fontSize color:color appendFront:YES];
}


+ (NSMutableAttributedString *)attributedString:(NSString *)imageName text:(NSString *)textStr font:(CGFloat)fontSize color:(UIColor *)color appendFront:(BOOL)front
{
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    
    UIImage *image = [UIImage imageNamed:imageName];
    image = [UIImage imageWithCGImage:image.CGImage scale:2.0 orientation:UIImageOrientationUp];
    
    NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:image contentMode:UIViewContentModeLeft attachmentSize:image.size alignToFont:FONT(fontSize) alignment:YYTextVerticalAlignmentCenter];
    
    
    NSAttributedString *attributedS = [[NSAttributedString alloc] initWithString:textStr];
    
    ///把图片富文本加到 文字前面,
    if (front) { //图片在前面
        
        [text appendAttributedString:attachText];
        [text appendString:@" "];
        [text appendAttributedString:attributedS];
        
        
    } else {
        //图片在后
        [text appendAttributedString:attributedS];
        [text appendString:@" "];
        [text appendAttributedString:attachText];
        
    }
    
    text.font = FONT(fontSize);
    text.color = color;
    
    return text;
}


+ (NSDictionary *)getParagraphStyleFontSize:(CGFloat)font color:(UIColor *)color firstLineHeadIndent:(CGFloat)headIndent
{
    ///结构体数组,  段落布局
    ///   NSParagraphStyleAttributeName 段落的风格（设置首行，行间距，对齐方式什么的）看自己需要什么属性，写什么
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 1.5f;/// 字体的行间距
    paragraphStyle.firstLineHeadIndent = headIndent;///首行缩进
    paragraphStyle.alignment = NSTextAlignmentJustified;///（两端对齐的）文本对齐方式：（左，中，右，两端对齐，自然）
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;///结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")
    paragraphStyle.minimumLineHeight = 10;///最低行高
    paragraphStyle.maximumLineHeight = 20;///最大行高
    ///paragraphStyle.paragraphSpacing = 5;///段与段之间的间距
    /// paragraphStyle.paragraphSpacingBefore = 22.0f;///段首行空白空间/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */
    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;///从左到右的书写方向（一共➡️三种）
    paragraphStyle.lineHeightMultiple = 15;/* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */
    NSDictionary *dict = @{
                           NSParagraphStyleAttributeName : paragraphStyle,
                           NSFontAttributeName: FONT(font),
                           NSForegroundColorAttributeName : color
                           };
    return dict;
}

+ (NSMutableAttributedString *)attributedPriceString:(NSString *)currentPrice text:(NSString *)originalPrice {
    
    NSString *marketPrice = [NSString stringWithFormat:@"￥%@",originalPrice];
    
    NSString *priceStr = [NSString stringWithFormat:@"￥%@ ￥%@",currentPrice,originalPrice];
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:priceStr];
    NSRange range = [priceStr rangeOfString:@" "];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithBLString:@"#FF5906"] range:NSMakeRange(0, range.location)];
    NSUInteger length = priceStr.length;
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range.location+1, length-range.location-1)];
    
    [string addAttributes:@{
                             NSStrikethroughStyleAttributeName:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle),
                             NSStrikethroughColorAttributeName:
                                 [UIColor redColor],
                             NSBaselineOffsetAttributeName:
                                 @(0)
                             } range:[priceStr rangeOfString:marketPrice]];
    return string;
    
}

+(NSString *)liveStateUpAt:(NSString *)upAt downAt:(NSString *)downAt {
    
    NSDate *dateNow = [NSDate date];
    NSString *nowStr = [NSString stringWithFormat:@"%ld000", (long)[dateNow timeIntervalSince1970]];
    NSString *nowHalfStr = [NSString stringWithFormat:@"%ld000", (long)([dateNow timeIntervalSince1970]+0.5*60*60)];
    
    NSString *str;
    if ([upAt doubleValue]>[nowStr doubleValue]) {
        if ([upAt doubleValue]<[nowHalfStr doubleValue]) {
            str = @"即将开始";
        }else {
            str = @"未开始";
        }
    }else if([downAt doubleValue]<[nowStr doubleValue]) {
        str = @"已结束";
    }else {
        str = @"直播中";
    }
    
    return str;
}


@end
